<?php
namespace control;
/*
*消息中心类
*/

class messageClass extends adIndexClass
{
    public array $messageType = ['公司通知', '公司动态'];
    private const title = '消息中心类';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        $tr = [
            'text'          => [
                'name'  => L('person.table.nei_rong'),
                'width' => 1200,
            ],
            'time'  => [
                'name'  => L('person.table.txsj'),
                'width' => 200,
                'sort' => 1,
            ],

        ];
        switch ($fun) {
            case 'processedSearch':
                $tr = array_merge($tr,
                    [
                        'seeTime'         =>
                            [
                                'name'  => L('person.table.cksj'),
                                'width' => 200,
                                'sort' => 1,
                            ]
                    ]
                );
                break;
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('person.table.nei_rong') => text(array("name" => "text")).
                        hidden(["name" => "see", 'value' => '否']),
                    L('person.table.time')  => text(["name" => "date", 'laydate' => ['range' => '~', 'type' => 'date']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 待阅 - 列表页 - 查询条件
     *
     * @param string $see
     * @return string
     */
    public function home()
    {
        $html = $this->homeOptions(false);
        //返回
        $button = "<span onclick=\"layer('message','layerModel',{type:'read'})\" class='spanButton'>".L('person.table.mark')."</span>\n";
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*列表页-查询条件*/
    public function processedOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('person.table.nei_rong') => text(array("name" => "text")).
                        hidden(["name" => "see", 'value' => '是']),
                ],
                [
                    L('person.table.seeTime')  => text(["name" => "date", "class" => "width300", 'laydate' => [ 'range' => '~', 'type'=> 'datetime']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 已阅 - 列表页 - 查询条件
     *
     */
    public function processed()
    {
        $html = $this->processedOptions(false);
        //返回
        $button = "";
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function processedSearch()
    {
        return $this->homeSearch();
    }

    /**
     * 查询结果
     *
     * @return string
     */
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "text" => $this->post('text'),//内容
        );
        //全等查询数组
        $equal = array(
            "see" => $this->post('see'),//阅读
        );
        $and = " AND stid = '".self::$stid."' ";
        if (!empty($this->post('date'))) {
            $and .= self::timeComparison($this->post('date'), 'time', ($this->post('see') == '否') ? 'seeTime' : 'time');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => "message", "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        if ($this->post('see') == '否') {
            //表格控件区
            $liButton = array(
                $this->checkAll("listForm", "listId")
            );
        } else {
            //表格控件区
            $liButton = array('');
        }
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = [];
            if ($array['see'] == '否') {
                //列表控件
                $dominate['box'] = array("name" => "listId", "value" => $array['id']);
            }
            $info = query('audit', " id ='$array[typeId]'");
            if (in_array($array['type'], $this->messageType)) {
                $click= "window.open('" . root . "control/adIndex.html?cla=notification&fun=previewPage&id={$array['typeId']}')";
            }else if (!empty($array['targetCla']) && !empty($array['targetFun']) && empty($info['id'])) {
                $click= $array['see'] == '否' ?
                    "see('{$array['type']}','{$array['targetCla']}','{$array['targetFun']}','{$array['typeId']}','{$array['id']}')" :
                    "newIframe('{$array['type']}详情','".root."control/adIndex.html?cla={$array['targetCla']}&fun={$array['targetFun']}&id={$array['typeId']}')";
            } else {
                $click= $array['see'] == '否' ?
                    "see('{$array['type']}','{$info['targetCla']}','{$info['targetFun']}','{$info['targetId']}','{$array['id']}')" :
                    "newIframe('{$array['type']}详情','".root."control/adIndex.html?cla={$info['targetCla']}&fun={$info['targetFun']}&id={$info['targetId']}')";
            }
            $dominate['detail'] = ["title" => self::title . "详情", "click" => $click];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //返回
        $button = '';
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'];
        $json['html'] .= <<<EOT
        <script>
        function see(type,targetCla,targetFun,targetId,messageId){
            $.post(root+'control/adIndex.html?cla=homepage&fun=see',{messageId:messageId},function(res) {
               if (res.warn ===2){
                    newIframe(type+'详情',root+'control/adIndex.html?cla='+targetCla+'&fun='+targetFun+'&id='+targetId)
               }else{
                   warn(res.warn);
               }
            },'json')
        }
        </script>
EOT;
        return json_encode($json, 320);
    }

    /**
     * 弹窗
     * @return bool|string
     */
    public function layerModel()
    {
        //准备数据
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('person.table.tip')."：" => L('person.table.markMessageDone'),
            )
        )));

        return $this->layer(array("title" => L('person.table.biao_ji'), "height" => 180, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     *弹窗编辑
     */
    public function layerModelEdit()
    {
        $listId = $this->post('listId');
        if (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('person.table.chooseMarkMessage');
        } else {
            $json['warn'] = update(array("table" => "message", "field" => array('see' => '是', 'seeTime' => $this->time), "where" => "id IN ('" . implode("','", $listId) . "') and see = '否'"));
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $text =  str_replace(['{{staffName}}'],[$this->control['name']],L('person.table.markDoneMessage'));
            $this->logText(array("type" => "message", "text" => $text));
            //返回
            $_SESSION['warn'] = L('person.table.bjcg');
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    public function read(){
        if (!$this->power('message','see')){
            $_SESSION['warn'] = "你还没有查看的权限";
        }else{
            $num = self::total(['table'=>'message','where'=>"stid = '".self::$stid."' and see = '否'"]);
            $json['warn'] = update(array("table" => "message", "field" => array('see' => '是', 'seeTime' => $this->time), "where" => "stid = '".self::$stid."' and see = '否'"));
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                //添加日志
                $text =  $this->control['name']."把消息全部设为了已读";
                $this->logText(array("type" => "message", "text" => $text));
                //返回
                $_SESSION['warn'] = "标记了{$num}条消息为已读";
            }
        }
        header("Location: ".root . 'control/adIndex.html?cla=homepage&fun=home');
    }
}
